package com.zxkj.ssm.weixin.shop.oss;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云存储
 *
 * @author cxy
 * @email 2273803419@qq.com
 * @date 2017-03-26 16:22
 */
public class MinioStorageService extends CloudStorageService {
    private MinioClient client;

    public MinioStorageService(CloudStorageConfig config) {
        this.config = config;
        //初始化
        init();
    }

    private void init() {
        client = MinioClient.builder()
                .endpoint(config.getMinioDomain())
                .credentials(config.getMinioAccessKey(), config.getMinioSecretKey())
                .build();

    }

    @Override
    public String upload(MultipartFile file) throws Exception {

        String fileName = file.getOriginalFilename();
        try (InputStream in = file.getInputStream()) {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(config.getMinioBucketName())
                    .object(fileName)
                    .stream(in, file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            client.putObject(putObjectArgs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return config.getMinioDomain() + "/" +config.getMinioBucketName()+"/"+ fileName;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {


        return config.getMinioDomain() + "/" + path;
    }
}
